package com.hmdp.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; // 关键导入
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryBlogById(Integer current) {
        //根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog->
        {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        //查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }
        //查询blog有关的用户
        queryBlogUser(blog);
        //查询blog是否被点赞了
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if(user==null){
            //未登入直接返回
            return;
        }
        //获取登入用户
        Long userid= user.getId();
        // 判断当前用户是否已经点赞
        String key="blog:liked:"+blog.getId();
       Double scroe= stringRedisTemplate.opsForZSet().score(key, userid.toString());
    blog.setIsLike(scroe!=null);
    }

    @Override
    public Result likeBlog(Long id) {
        //获取登入用户
        Long userid= UserHolder.getUser().getId();
        // 判断当前用户是否已经点赞
        String key="blog:liked:"+id;
        //Boolean isMember= stringRedisTemplate.opsForSet().isMember(key, userid.toString());
        Double score=stringRedisTemplate.opsForZSet().score(key, userid.toString());
        if(score==null){
            //如果未点赞，可以点赞
            //数据库点赞数+1
            boolean isSuccess=update().setSql("liked=liked+1").eq("id",id).update();
          //保存用户到redis的set集合 zadd key value score
          if(isSuccess){
              stringRedisTemplate.opsForZSet().add(key,userid.toString(),System.currentTimeMillis());
          }

        }else{
            //如果点赞，取消点赞
            //数据库点赞数-1
            boolean isSuccess=update().setSql("liked=liked-1").eq("id",id).update();
            //把用户从redis的set集合移除
            if(isSuccess){
                stringRedisTemplate.opsForZSet().remove(key,userid.toString());
            }
        }

      return Result.ok();
    }
    @Override
    public Result queryBlogLikes(Long id){
        String key=BLOG_LIKED_KEY+id;
        //查询top5 的点赞用户 zrange key 0 4
    Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
    if(top5==null || top5.isEmpty()){
        return Result.ok(Collections.emptyList());
    }
    //解析出其中的用户ID
    List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
    String idStr= StrUtil.join(",",ids);
    //根据用户id查询用户
List<UserDTO> userDTOS=userService.query()
        .in("id",ids).last("ORDER BY FIELD(id,"+idStr+")").list()
        .stream()
        .map(user-> BeanUtil.copyProperties(user,UserDTO.class))
        .collect(Collectors.toList());
    //返回

        return Result.ok(userDTOS);
}
    private void queryBlogUser(Blog blog){
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
